# coding=utf-8

import socket
import threading
import time

PORT = 4333     # 端口号


class Client:

    def __init__(self, hostname, port=PORT):
        self.sock = socket.socket()
        try:
            # 若服务器没有启动，connect()方法将返回异常
            self.sock.connect((hostname, port))
        except socket.error:
            print "Connection failed."
        else:
            self._perform()

    # 接收消息
    def _receive(self):
        while True:
            try:
                data = self.sock.recv(1024)
                disconnected = not data
            except socket.error:
                disconnected = True
            if disconnected:
                print "Disconnect."
                break
            else:
                if data[-2:] == "\r\n":
                    data = data[0:-2]
                print data

    # 发送消息
    def _send(self):
        while True:
            line = raw_input()
            if line == "quit":
                break
            self.sock.send(line + "\r\n")

    def _perform(self):
        thread1 = threading.Thread(target=self._receive)
        thread2 = threading.Thread(target=self._send)
        # 设置为守护线程，主线程结束，则子线程也结束
        thread1.setDaemon(True)
        thread2.setDaemon(True)
        thread1.start()
        thread2.start()
        # self.send()
        # self.receive()
        while True:
            time.sleep(2)
            # 每两秒检查一次，若有任一线程退出，主线程结束
            if not thread1.is_alive() or not thread2.is_alive():
                break

if __name__ == "__main__":
    hostname = socket.gethostname()
    client = Client(hostname, PORT)
